package com.yuzhitong.shapi.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.core.content.res.ResourcesCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.alibaba.fastjson.JSON;
import com.bytedance.sdk.dp.DPArticleLevel;
import com.bytedance.sdk.dp.DPComponentPosition;
import com.bytedance.sdk.dp.DPSdk;
import com.bytedance.sdk.dp.DPWidgetTextChainParams;
import com.bytedance.sdk.dp.DPWidgetVideoCardParams;
import com.bytedance.sdk.dp.IDPAdListener;
import com.bytedance.sdk.dp.IDPElement;
import com.bytedance.sdk.dp.IDPTextChainListener;
import com.bytedance.sdk.dp.IDPVideoCardListener;
import com.bytedance.sdk.dp.IDPWidgetFactory;
import com.yuzhitong.shapi.R;
import com.yuzhitong.shapi.activity.CategoryActivity;
import a.a.a.MyApplication;

import com.yuzhitong.shapi.activity.PlayNewActivity;
import com.yuzhitong.shapi.base.BaseMvpFragment;
import com.yuzhitong.shapi.base.Contents;
import com.yuzhitong.shapi.base.recycler.BaseAdapter;
import com.yuzhitong.shapi.base.recycler.BaseViewHolder;
import com.yuzhitong.shapi.bean.MovieBean;
import com.yuzhitong.shapi.contract.MovieListContract;
import com.yuzhitong.shapi.presenter.MovieListPresenter;
import com.yuzhitong.shapi.util.AdUtilManage;
import com.yuzhitong.shapi.util.GlideUtil;
import com.yuzhitong.shapi.util.LoggerUtil;
import com.yuzhitong.shapi.util.StringUtil;
import com.yuzhitong.shapi.util.UiUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by Brsya
 * CreateDate: 2022/5/8  15:57
 * Description:
 * 影视列表
 */
public class MovieListFragment extends BaseMvpFragment<MovieListPresenter> implements MovieListContract.View {

    private TextView tvSortTitle;
    private TextView tvShowMore;
    private RecyclerView rlSortList;
    private RelativeLayout rlMovieAdText;
    private RelativeLayout rlMovieAdVideo;
    private RecyclerView rlRecommendList;
    private RelativeLayout flAdBox;
    private RecyclerView rlRecommendList2;
    private SwipeRefreshLayout srlRefresh;
    private TextView tvShowMoreDay;

    private BaseAdapter<MovieBean> sortAdapter;
    private BaseAdapter<MovieBean> DayHotAdapter;
    private BaseAdapter<MovieBean> DayHotAdapter2;

    // 改变上层搜索框文字
    private OnSearchTextChange onSearchTextChange;

    // 类型
    private String type;
    // 排序
    private String sort;
    private String adId;

    // 广告管理类
    private AdUtilManage adUtilManage;

    private boolean isPreload;
    private boolean isLoad = true;


    public static MovieListFragment newInstance(String type, String sort) {

        Bundle args = new Bundle();
        args.putString("type", type);
        args.putString("sort", sort);

        MovieListFragment fragment = new MovieListFragment();
        fragment.setArguments(args);
        return fragment;
    }

    public static MovieListFragment newInstance(String type, String sort, String sortName, boolean isPreload, String adId) {

        Bundle args = new Bundle();
        args.putString("type", type);
        args.putString("sort", sort);
        args.putString("sortName", sortName);
        args.putBoolean("isPreload", isPreload);
        args.putString("adId", adId);

        MovieListFragment fragment = new MovieListFragment();
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    protected void initView() {
        setContentViewId(R.layout.fragment_movie_list);
        tvSortTitle = findViewById(R.id.tv_sort_title);
        tvShowMore = findViewById(R.id.tv_show_more);
        rlSortList = findViewById(R.id.rl_sort_list);
        rlMovieAdVideo = findViewById(R.id.rl_movie_ad_video);
        rlRecommendList = findViewById(R.id.rl_recommend_list);
        rlMovieAdText = findViewById(R.id.rl_movie_ad_text);
        flAdBox = findViewById(R.id.fl_ad_box);
        rlRecommendList2 = findViewById(R.id.rl_recommend_list_2);
        srlRefresh = findViewById(R.id.srl_refresh);
        tvShowMoreDay = findViewById(R.id.tv_show_more_day);
    }

    @Override
    protected void initData() {
        if (getArguments() != null) {
            type = getArguments().getString("type");
            sort = getArguments().getString("sort");
            String sortName = getArguments().getString("sortName");
            adId = getArguments().getString("adId");
            tvSortTitle.setText(sortName);
            isPreload = getArguments().getBoolean("isPreload", false);
        }

        tvShowMore.setOnClickListener(v -> {
            // 2022/5/8 进入筛选页
            Intent intent = new Intent(getActivity(), CategoryActivity.class);
            intent.putExtra(Contents.INTENT_MOVIE_TYPE, type);
            intent.putExtra(Contents.INTENT_MOVIE_SORT, sort);
            startActivity(intent);
        });

        rlSortList.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
        rlSortList.setAdapter(sortAdapter = new BaseAdapter<MovieBean>() {
            @Override
            public BaseViewHolder onCreate(ViewGroup parent, int viewType) {
                View itemView = LayoutInflater.from(getContext()).inflate(R.layout.item_movie_line, parent, false);
                return new BaseViewHolder(itemView);
            }

            @Override
            public void onBind(BaseViewHolder viewHolder, int RealPosition, MovieBean data) {
                ImageView ivMovieImg = viewHolder.findViewById(R.id.iv_movie_img);
                TextView tvMovieTitle = viewHolder.findViewById(R.id.tv_movie_title);
                viewHolder.findViewById(R.id.sv_score_box).setVisibility(View.GONE);

                tvMovieTitle.setText(data.getName());
                GlideUtil.loadRound(ivMovieImg, data.getCoverUrl(), 4);

                if (RealPosition == getDataList().size() - 1) {
                    viewHolder.findViewById(R.id.v_end_padding).setVisibility(View.VISIBLE);
                }else{
                    viewHolder.findViewById(R.id.v_end_padding).setVisibility(View.GONE);
                }


            }
        });

        sortAdapter.setOnItemClickListener((position, data) -> {
            Intent intent = new Intent(getActivity(), PlayNewActivity.class);
            intent.putExtra(Contents.INTENT_MOVIE_DETAIL, data);
            startActivity(intent);
        });


        rlRecommendList.setLayoutManager(new GridLayoutManager(getContext(), 3));
        rlRecommendList.setAdapter(DayHotAdapter = new BaseAdapter<MovieBean>() {
            @Override
            public BaseViewHolder onCreate(ViewGroup parent, int viewType) {
                View itemView = LayoutInflater.from(getContext()).inflate(R.layout.item_movie, parent, false);
                return new BaseViewHolder(itemView);
            }

            @Override
            public void onBind(BaseViewHolder viewHolder, int RealPosition, MovieBean data) {
                ImageView ivMovieImg = viewHolder.findViewById(R.id.iv_movie_img);
                TextView tvMovieTitle = viewHolder.findViewById(R.id.tv_movie_title);
                viewHolder.findViewById(R.id.sv_score_box).setVisibility(View.GONE);

                tvMovieTitle.setText(data.getName());
                GlideUtil.loadRound(ivMovieImg, data.getCoverUrl(), 4);
            }
        });
        DayHotAdapter.setOnItemClickListener((position, data) -> {
            Intent intent = new Intent(getActivity(), PlayNewActivity.class);
            intent.putExtra(Contents.INTENT_MOVIE_DETAIL, data);
            startActivity(intent);
        });
        rlRecommendList2.setLayoutManager(new GridLayoutManager(getContext(), 3));
        rlRecommendList2.setAdapter(DayHotAdapter2 = new BaseAdapter<MovieBean>() {
            @Override
            public BaseViewHolder onCreate(ViewGroup parent, int viewType) {
                View itemView = LayoutInflater.from(getContext()).inflate(R.layout.item_movie, parent, false);
                return new BaseViewHolder(itemView);
            }

            @Override
            public void onBind(BaseViewHolder viewHolder, int RealPosition, MovieBean data) {
                ImageView ivMovieImg = viewHolder.findViewById(R.id.iv_movie_img);
                TextView tvMovieTitle = viewHolder.findViewById(R.id.tv_movie_title);
                viewHolder.findViewById(R.id.sv_score_box).setVisibility(View.GONE);

                tvMovieTitle.setText(data.getName());
                GlideUtil.loadRound(ivMovieImg, data.getCoverUrl(), 4);
            }
        });
        DayHotAdapter2.setOnItemClickListener((position, data) -> {
            Intent intent = new Intent(getActivity(), PlayNewActivity.class);
            intent.putExtra(Contents.INTENT_MOVIE_DETAIL, data);
            startActivity(intent);
        });

        srlRefresh.setOnRefreshListener(this::loadData);

        tvShowMoreDay.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), CategoryActivity.class);
            intent.putExtra(Contents.INTENT_MOVIE_TYPE, type);
            startActivity(intent);
        });

        if (isPreload) {
            try {
                String hot = MyApplication.aCache.getAsString(Contents.CACHE_KEY_CATEGORY_HOT);
                if (!StringUtil.isEmpty(hot)) {
                    List<MovieBean> list = JSON.parseArray(hot, MovieBean.class);
                    showHot(list);
                } else {
                    LoggerUtil.e("热门数据为空");
                }
                String day = MyApplication.aCache.getAsString(Contents.CACHE_KEY_CATEGORY_DAY);
                if (!StringUtil.isEmpty(day)) {
                    List<MovieBean> list = JSON.parseArray(day, MovieBean.class);
                    showDayHot(list);
                } else {
                    LoggerUtil.e("今日数据为空");
                }
            } catch (Exception e) {
                // 解析失败不做处理,继续请求网络数据
                isPreload = false;
            }
        }
    }


    private void initTTAd() {

        if (!DPSdk.isInitSuccess()) {
            LoggerUtil.e("小视频加载失败: 穿山甲初始化失败");
            return;
        }
        if (!MyApplication.isOpenAd()) {
            return;
        }

        getVideo();

        //        new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
        //            @Override
        //            public void run() {
        //                getText();
        //            }
        //        }, 1000);
        //
        //        new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
        //            @Override
        //            public void run() {
        //                getImg();
        //            }
        //        }, 1500);
    }

    private void getImg() {
        // 加载图文广告
        adUtilManage = AdUtilManage.initShow(getActivity(), flAdBox, StringUtil.isEmpty(adId) ? Contents.AD_TT_SDK_MOVIE_ID : adId);
    }

    private void getVideo() {
        // 加载穿山甲小视频卡片
        DPSdk.factory().loadCustomVideoCard(
                DPWidgetVideoCardParams.obtain()
                        .cardHeight(134)
                        .listener(new IDPVideoCardListener() {
                            @Override
                            public void onDPItemClick(Map<String, Object> map) {
                                super.onDPItemClick(map);
                                //                                if (getActivity() != null) {
                                //                                    getActivity().getWindow().setNavigationBarColor(0xFF000000);
                                //                                }
                            }

                            @Override
                            public void onDPLSwipeEnter() {
                                super.onDPLSwipeEnter();
                                //                                if (getActivity() != null) {
                                //                                    getActivity().getWindow().setNavigationBarColor(0xFF000000);
                                //                                }
                            }
                        })
                        .adListener(new IDPAdListener() {

                        })
                        .dislikeListener(getActivity(), s -> LoggerUtil.e("小视频onSelected: " + s))
                , new IDPWidgetFactory.Callback() {

                    @Override
                    public void onError(int i, String s) {
                        LoggerUtil.e("小视频加载失败: " + i + " --- " + s);
                        getText();
                    }

                    @Override
                    public void onSuccess(IDPElement idpElement) {
                        View view = idpElement.getView();
                        if (view == null || rlMovieAdVideo == null) {
                            return;
                        }
                        rlMovieAdVideo.setVisibility(View.VISIBLE);
                        rlMovieAdVideo.removeAllViews();
                        ViewGroup viewGroup = (ViewGroup) view.getParent();
                        if (viewGroup != null) {
                            viewGroup.removeAllViews();
                        }
                        rlMovieAdVideo.addView(view);

                        getText();
                    }
                });
    }

    private void getText() {
        // 加载穿山甲气泡
        DPSdk.factory().loadTextChain(
                DPWidgetTextChainParams.obtain()
                        .articleLevel(DPArticleLevel.LEVEL_2) // 内容等级
                        .componentPosition(DPComponentPosition.TAB2)
                        .animationDuration(300) // 动画时长
                        //                        .backgroundColor(0xFFE7F6FF)// 背景颜色
                        .iconDrawable(ResourcesCompat.getDrawable(getResources(), R.mipmap.icon_movie_home_hot, null))
                        .iconWidth(15)
                        .iconHeight(17)
                        .showDuration(4000) // 停留时长
                        .showWatch(true) // 是否展示观看信息
                        //                        .titleTextColor(0x880560D1) // 标题文字颜色
                        .titleTextSize(16) // 标题文字大小
                        //                        .watchTextColor(0x880560D1) // 观看文字颜色
                        .watchTextSize(16) // 观看文字大小
                        .listener(new IDPTextChainListener() {})
                        .adListener(new IDPAdListener() {})

                , new IDPWidgetFactory.Callback() {
                    @Override
                    public void onError(int i, String s) {
                        LoggerUtil.e("气泡加载失败: " + i + " --- " + s);
                        getImg();
                    }

                    @Override
                    public void onSuccess(IDPElement idpElement) {
                        View view = idpElement.getView();
                        if (view == null || rlMovieAdText == null) {
                            return;
                        }
                        rlMovieAdText.removeAllViews();
                        rlMovieAdText.setVisibility(View.VISIBLE);
                        ViewGroup viewGroup = (ViewGroup) view.getParent();
                        if (viewGroup != null) {
                            viewGroup.removeAllViews();
                        }
                        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
                                RelativeLayout.LayoutParams.MATCH_PARENT
                                , UiUtil.dpToPx(getActivity(), 32));
                        view.setLayoutParams(lp);
                        rlMovieAdText.addView(view);

                        getImg();
                    }
                });
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            isLoad = false;
            if (!isPreload) {
                loadData();
            } else {
                initTTAd();
                isPreload = false;
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (getActivity() != null) {
            getActivity().getWindow().setNavigationBarColor(0xFFFFFFFF);
            getActivity().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        }
        if (isLoad) {
            isLoad = false;
            if (!isPreload) {
                loadData();
            } else {
                initTTAd();
                isPreload = false;
            }
        }
    }

    private void loadData() {
        isLoad = false;
        initTTAd();
        if (isPreload) {
            isPreload = false;
            return;
        }
        presenter.getHot(type, sort);
        presenter.getDayHot(1, type);
    }

    @Override
    public void hideLoading() {
        super.hideLoading();
        srlRefresh.setRefreshing(false);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        AdUtilManage.destroy(adUtilManage);
    }

    @Override
    protected void initPresenter() {
        presenter = new MovieListPresenter();
        presenter.attachView(this);
    }

    @Override
    public void showHot(List<MovieBean> categoryBeans) {
        sortAdapter.setDataList(categoryBeans);
        sortAdapter.notifyDataSetChanged();

        if (onSearchTextChange != null) {
            if (categoryBeans != null && categoryBeans.size() > 0) {
                onSearchTextChange.changeSearchText(categoryBeans.get(0).getName());
            }
        }
    }

    @Override
    public void showDayHot(List<MovieBean> categoryBeans) {
        if (categoryBeans == null) {
            return;
        }

        if (categoryBeans.size() <= 9) {
            DayHotAdapter.setDataList(categoryBeans);
            DayHotAdapter.notifyDataSetChanged();
            rlRecommendList2.setVisibility(View.GONE);
            return;
        }
        List<MovieBean> beans1 = new ArrayList<>();
        List<MovieBean> beans2 = new ArrayList<>();
        for (int i = 0; i < categoryBeans.size(); i++) {
            if (i < 9) {
                beans1.add(categoryBeans.get(i));
            } else {
                beans2.add(categoryBeans.get(i));
            }
        }
        DayHotAdapter.setDataList(beans1);
        DayHotAdapter.notifyDataSetChanged();

        DayHotAdapter2.setDataList(beans2);
        DayHotAdapter2.notifyDataSetChanged();
    }

    @Override
    public void showNoMore() {
    }


    public void setOnSearchTextChange(OnSearchTextChange onSearchTextChange) {
        this.onSearchTextChange = onSearchTextChange;
    }

    public interface OnSearchTextChange {
        void changeSearchText(String text);
    }
}
